﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CPF.Controls;
using WampSharp.V2.Client;
using WampSharp.V2;
using WampShare;

namespace DesktopCam
{
    internal class WampFunc
    {
        private static  IWampRealmProxy realmProxy;
        private static ICamService proxy;


        static WampFunc()
        {
           // InitWamp();
        }
        public static async Task InitWamp()
        {
            //await Task.Delay(2000).ConfigureAwait(false);

            DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();

            IWampChannel channel = channelFactory.CreateJsonChannel(ICamService.Location, "realm1");

            realmProxy = channel.RealmProxy;

            await channel.Open().ConfigureAwait(false);

            await Console.Out.WriteLineAsync("连接成功，cpf client is running");

            proxy =  channel.RealmProxy.Services.GetCalleeProxy<ICamService>();
        }

        public static void SubscribeOpenCam(Action<byte[]> action)
        {
            IDisposable subscription = realmProxy.Services.GetSubject<byte[]>(ICamService.OpenCamTopic)
                         .Subscribe(x =>
                         {
                             //Console.WriteLine($"open: {x.Length}");
                             action(x);
                         },
                         ex => { Console.WriteLine($"发送出错：{ex}"); });
        }

        public static void SubscribeCloseCam(Action<string> action)
        {
            IDisposable subscription = realmProxy.Services.GetSubject<string>(ICamService.CloseCamTopic)
                         .Subscribe(x =>
                         {
                             Console.WriteLine($"close: {x}");
                             action(x);
                         }, ex => { Console.WriteLine($"关闭出错：{ex}"); });

        }

        public static async Task OpenCam()
        {
            string r =await proxy.OpenCam();
            await Console.Out.WriteLineAsync(r);
            //await Task.Delay(4000);
            //await CloseCam();
        }

        public static async Task CloseCam()
        {
            string r =await proxy.CloseCam();
            await Console.Out.WriteLineAsync(r);
        }
    }
}
